import mixin from "../../utils/mixin";
const app = getApp();
Page({
  data: {
    timeData: {
      // 倒计时秒数
      seconds: 0
    },
    mobile: '18385248827',
    code: '',
    isShow: true,
  },
  behaviors: [mixin],
  onLoad(params) {
    this.redirectUrl = params.redirectUrl
  },
  countDownChange(ev) {
    this.setData({
      timeData: ev.detail,
    })
  },

  valideMobile(mobile) {
    const reg = /^(?:(?:\+|00)86)?1[3-9]\d{9}$/
    const result = reg.test(mobile)
    if (!result) {
      wx.utils.toast('手机号格式错误', 'error')
    }
    return result
  },
  valideCode(code) {
    const reg = /^\d{6}$/
    const result = reg.test(code)
    if (!result) {
      wx.utils.toast('验证码格式错误', 'error')
    }
    return result
  },
  async getCode() {
    const { mobile } = this.data
    if (!this.valideMobile(mobile)) return
    const { data } = await wx.http.get('/code', {
      mobile
    })
    wx.utils.toast('发送成功')
    this.setData({
      code: data.code,
      isShow: false
    })
  },
  async login() {
    const { mobile, code } = this.data
    if (!this.valideMobile(mobile)) return
    if (!this.valideCode(code)) return
    const { data } = await wx.http.post('/login', { mobile, code })
    app.setToken(data.token)
    const url = this.redirectUrl || '/pages/my/index'
    if (this.isTabBar(url)) {
      wx.switchTab({
        url
      });
    } else {
      wx.redirectTo({
        url
      });
    }
  },

  countFinish() {
    this.setData({
      isShow: true
    })
  }
})
